package com.frogs.ucenter.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.OrderStatusEnum;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.ucenter.component.RsyncHelper;
import com.frogs.ucenter.component.UserPermissionHelper;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.service.OrderService;
import com.frogs.ucenter.service.UserService;

/**
 * 验证检查类
 * @author wushubin
 *
 */
@Controller
public class OrderController extends BaseController3 {

	private static Logger log = LoggerFactory.getLogger(OrderController.class);

	private static final String LIST_VIEW = "order/list";
	private static final String DETAIL_VIEW = "order/detail";
	private static final String DELETE_VIEW = "order/delete";
	private static final String HOME_VIEW = "order/index";
	
	private static final String ORDER_PHONE_BIND = "order/phone/bind";
	private static final String ORDER_PHONE_UNBIND = "order/phone/unbind";
	private static final String LIST = "/order/list";
	private static final String DETAIL = "/order/detail";
	private static final String DELETE = "/order/delete";
	private static final String IMPORT = "/order/import";
	private static final String HOME = "/order/index";
	
	
	@Resource
	private OrderService orderService;
	@Resource
	private UserService userService;
	
	@Resource
	private UserPermissionHelper userPermissionHelper;
	@Resource
	private RsyncHelper rsyncHelper;
	
	@RequestMapping(DELETE)
    public void delete(HttpServletRequest request ,ModelMap model,Integer id) throws Exception {
		
		
		try {
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		model.addAttribute("result", orderService.deleteOrder(user.getId(), id));
    		
		} catch (Exception e) {
			log.error("func[delete] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
    }
	
	@RequestMapping(LIST)
    public void list(HttpServletRequest request ,ModelMap model) throws Exception {
    	try {
    		HttpRequestInfo reqInfo = new HttpRequestInfo(request);
    		
    		int pageSize = reqInfo.getIntParameter("pageSize",10);
    		int status = reqInfo.getIntParameter(ApiUrlParamEnum.status.getParamName(),OrderStatusEnum.ORDER_STATUS_YES.getId());
    		String produceSource = reqInfo.getParameter(ApiUrlParamEnum.produceSource.getParamName(),"");
    		int produceSourceType = reqInfo.getIntAttribute(ApiUrlParamEnum.produceSourceType.getParamName(),0);
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
			JSONObject result = orderService.getOrderEveryStatusList(1, pageSize,user.getId(),status,produceSource,produceSourceType);
    		if(result != null){
    			JSONObject res = result.getJSONObject("response");
    			model.addAttribute("response", res);
    		}
		} catch (Exception e) {
			log.error("func[list] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
    }
	
	@RequestMapping(DETAIL)
    public String detail(HttpServletRequest request ,ModelMap model,Integer id) throws Exception {
    	try {
    		
    		
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		model.addAttribute("order", orderService.showOrder(user.getId(),id));
    		
		} catch (Exception e) {
			log.error("func[detail] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
    	return DETAIL_VIEW;
    }
	
	@RequestMapping(HOME)
    public String home(HttpServletRequest request, ModelMap model) {
    	try {
    		HttpRequestInfo reqInfo = new HttpRequestInfo(request);
    		
    		
    		Integer pageNo = reqInfo.getIntParameter("pageNo", 0);
    		Integer pageSize = reqInfo.getIntParameter("pageSize", 20);
    		
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		JSONObject object = orderService.getOrderList(pageNo, pageSize, user.getId());
    		model.addAttribute("list",object );
    		
		} catch (Exception e) {
			log.error("func[home] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
    	return HOME_VIEW;
    }
	
	@RequestMapping(ORDER_PHONE_BIND)
	public JSONObject bindOrderPhone(HttpServletRequest request, ModelMap model) {
		try {
			HttpRequestInfo reqInfo = new HttpRequestInfo(request);
			
			UserBaseAccountInfo user = userPermissionHelper.getUser(request);
			Map<String,Object> baseInfo = new HashMap<String,Object>();
			String orderPhone = reqInfo.getParameter(ApiUrlParamEnum.orderPhone.getParamName(), "");
			String bindPhone = reqInfo.getParameter(ApiUrlParamEnum.phone.getParamName(), "");
			if(null == user) {
				throw new Exception("用户验证出错");
			}
			if(StringUtil.isEmpty(bindPhone)) {
				throw new Exception("请输入手机号码");
			}
			if(!StringUtil.isEmpty(orderPhone)) {
				JSONObject result = orderService.bindingOrderPhone(bindPhone, user.getId());
				if(ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue("code")) {
					baseInfo.put(ApiUrlParamEnum.userId.getParamName(), user.getId());
					baseInfo.put(ApiUrlParamEnum.orderPhone.getParamName(), orderPhone);
					userService.updateUserBaseInfo(baseInfo);
					rsyncHelper.rsyncPhoneAddress(user.getId(), bindPhone);
				}
				return result;
			}
			
			
		} catch (Exception e) {
			log.error("func[home] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
		}
		return null;
	}
	
	@RequestMapping(ORDER_PHONE_UNBIND)
	public JSONObject unBbindOrderPhone(HttpServletRequest request, ModelMap model) {
		try {
			HttpRequestInfo reqInfo = new HttpRequestInfo(request);
			
			UserBaseAccountInfo user = userPermissionHelper.getUser(request);
			Map<String,Object> baseInfo = new HashMap<String,Object>();
			String orderPhone = reqInfo.getParameter(ApiUrlParamEnum.orderPhone.getParamName(), "");
			String bindPhone = reqInfo.getParameter(ApiUrlParamEnum.phone.getParamName(), "");
			if(null == user) {
				throw new Exception("用户验证出错");
			}
			if(StringUtil.isEmpty(bindPhone)) {
				throw new Exception("请输入手机号码");
			}
			if(!StringUtil.isEmpty(orderPhone)) {
				JSONObject result = orderService.unBindingOrderPhone(bindPhone, user.getId());
				if(ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue("code")) {
					baseInfo.put(ApiUrlParamEnum.userId.getParamName(), user.getId());
					
					baseInfo.put(ApiUrlParamEnum.orderPhone.getParamName(), orderPhone);
					userService.updateUserBaseInfo(baseInfo);
				}
				return result;
			}
			
			
		} catch (Exception e) {
			log.error("func[home] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
		}
		return null;
	}
	
	@RequestMapping(IMPORT)
	public JSONObject importOrderPhone(HttpServletRequest request, ModelMap model) {
		try {
			HttpRequestInfo reqInfo = new HttpRequestInfo(request);
			
			UserBaseAccountInfo user = userPermissionHelper.getUser(request);
			String orderPhone = reqInfo.getParameter(ApiUrlParamEnum.orderPhone.getParamName(), "");
			if(null == user) {
				throw new Exception("用户验证出错");
			}
			if(!StringUtil.isEmpty(orderPhone)) {
				JSONArray jsr = JSONObject.parseArray(orderPhone);
				String phones = "";
				if(!jsr.isEmpty()) {
					for(int i = 0; i< jsr.size(); i++) {
						phones += jsr.getJSONObject(i).getString("phone") + ",";
					}
					return orderService.syncOrders(phones, user.getId());
				}
			}
			
		} catch (Exception e) {
			log.error("func[importOrderPhone] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
		}
		return null;
	}
	
}
